$(function () {
    var selectedChannel;
    var selectedChannelId;
    var channels;
	var loaded= false;
	var showMessagesSucces=true;
	var selected;

    $('body').ready(
		function showChannels() {
		    var showChannelsUrl = "http://localhost:47952/ServiceChat.svc/ListChannels";

		    $.ajax({
		        type: "GET",
		        async: true,
		        url: showChannelsUrl,
		        data: null,
		        contentType: "application/json; charset=utf-8",
		        success: function (result) {
		            channels = result;
		            selectedChannel = result[0].Name;
		            selectedChannelId = result[0].ID;
					$('#selectedChannel').text('Channel '+selectedChannel);
		            for (var i = 0; i < result.length; i++) {
		           
						if(i === result.length-1)
						{
							$('#channelsArea').append('<li class="channel" id="lastChannel">' + result[i].Name + '</li>');
							$('#lastChannel').css({border:'0px'});
						}
						else
						{
							 $('#channelsArea').append('<li class="channel">' + result[i].Name + '</li>');
						}
		            }
					selected = $('#channelsArea .channel:first-child');
					selected.addClass('selectedClass');
					loaded = true;
		        }

		    });
		});

		function postMessage() {
		    var postMessagesURL = "http://localhost:47952/ServiceChat.svc/PostMessage";

		    var message = { Text: $('#postMessageField').val(), ChannelID: selectedChannelId, Posted: "" };
		    $.ajax({
		        type: "POST",
		        async: true,
		        url: postMessagesURL,
		        data: JSON.stringify(message),
		        contentType: "application/json; charset=utf-8",
		        success: function (result) {
		            $('#postMessageField').val("");
					$('#postMessageField').focus();
		        }
		    });
		}
		
	$('#postMessageField').bind('keydown',function(e){ 
	if(e.which ===13)
	{
		postMessage();
		return false;
	}
	
  });
		
    $('#submitMessage').click(postMessage);

    $('.channel').live("click",
		function selectChannel() {
		    var currentChannel = $(this).text();
			selected.removeClass('selectedClass');
			selected = $(this);
			$(this).addClass('selectedClass');
		    selectedChannel = currentChannel;
		    getIdOfCurrentChannel();
		    $('#selectedChannel').text(currentChannel);
		});

    $('#resetChannel').click(
            function resetChannel() {
			var resetChannelURL = "http://localhost:47952/ServiceChat.svc/ResetChannel";

		    var channel = { Name:selectedChannel, ID: selectedChannelId};
		    $.ajax({
		        type: "POST",
		        async: true,
		        url: resetChannelURL,
		        data: JSON.stringify(channel),
		        contentType: "application/json; charset=utf-8",
		        success: function (result) {
		            $('#postMessageField').val("")
		        }
		    });
            });

    function getIdOfCurrentChannel() {
        for (var i = 0; i < channels.length; i++) {
            if (channels[i].Name === selectedChannel) {
                selectedChannelId = channels[i].ID;
                break;
            }
        }
    }


    setInterval(function showMessages() {
        	if(loaded ===true && showMessagesSucces == true)
	{
		var showMessagesURL = "http://localhost:47952/ServiceChat.svc/ShowMessages";
        var channelAndNumber = { Channel: selectedChannel, NumberOfMessagesToBeShown: 20 };
		showMessagesSucces= false;

        $.ajax({
            type: "POST",
            async: true,
            url: showMessagesURL,
            data: JSON.stringify(channelAndNumber),
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                $('.message').remove();
                for (var i = 0; i < result.length; i++) {
                    var date = '[' + result[i].Posted + '] ';
                    $('#messagesContainer').append('<p class="message">' + date + result[i].Text + '</p>');
                }
				showMessagesSucces= true;
            }

        });
		}
    }, 500);
	
});